package org.coderfun.fieldmeta.controller.admin;



import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.coderfun.common.exception.AppException;
import org.coderfun.common.exception.ErrorCodeEnum;
import org.coderfun.fieldmeta.entity.TemplateFile;
import org.coderfun.fieldmeta.service.TemplateFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import klg.j2ee.common.model.EasyUIPage;
import klg.j2ee.common.model.JsonData;



/**
 *
 * 
 * Generated by fieldmeta at 2019-08-10T13:41:41+08:00
 *
 */

@Controller("adminTemplateFileController")
@RequestMapping("/admin/action/templatefile")
public class TemplateFileController {
	private static final Logger logger = LoggerFactory.getLogger(TemplateFileController.class);
	
	@Autowired
	TemplateFileService templateFileService;
	
	@Value("${fieldmeta.template.name}")
	String templateName = "";
	
	private void checkParams(TemplateFile templateFile){		
		boolean valid =  validDir(templateFile.getDir()) && validDir(templateFile.getGenFiledirPattern());
		if(!valid)
			throw new AppException(ErrorCodeEnum.INVALID_DIR);
	}
	
	private boolean validDir(String dir){
		return dir.startsWith("/") && dir.endsWith("/");
	}
	
	@ResponseBody
	@RequestMapping("/add")
	public JsonData add(
			@ModelAttribute TemplateFile templateFile) throws IOException{
		checkParams(templateFile);
		templateFileService.save(templateFile);
		return JsonData.success();
	}
	
	
	@ResponseBody
	@RequestMapping("/edit")
	public JsonData edit(
			@ModelAttribute TemplateFile templateFile) throws IOException{
		checkParams(templateFile);
		templateFileService.update(templateFile);
		return JsonData.success();
	}
	

	
	@ResponseBody
	@RequestMapping("/delete")
	public JsonData delete(
			@RequestParam Long id){
    	
		templateFileService.delete(id);
		return JsonData.success();
	}
	
	@ResponseBody
	@RequestMapping("/findpage")
	public EasyUIPage findpage(
			@ModelAttribute TemplateFile templateFile,
			@RequestParam int page,
			@RequestParam int rows){
		Pageable pageable=new PageRequest(page<1?0:page-1, rows, new Sort(Direction.DESC,"orderNum"));
		Page<TemplateFile> pageData=templateFileService.findPage(templateFile, pageable);
		return new EasyUIPage(pageData);
	}
	
	@ResponseBody
	@RequestMapping("/findlist")
	public JsonData findlist(
			@ModelAttribute TemplateFile templateFile){
		
		List<TemplateFile> listData=templateFileService.findList(templateFile, new Sort(Direction.DESC,"id"));
		return JsonData.success(listData);
	}
	
    @PostMapping("/upload")
    @ResponseBody
    public JsonData upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new AppException(ErrorCodeEnum.FILE_UPLOAD_FAILD);
        }      
        
        return JsonData.success(templateFileService.upload(file));
    }
	
    @RequestMapping("/tpfDownload")
    @ResponseBody
    public JsonData tpfDownload(Long tpfId, HttpServletResponse response){
    	TemplateFile templateFile = templateFileService.getById(tpfId);
    	try {
    		byte[] data = IOUtils.toByteArray(new FileInputStream(templateFileService.getFile(templateFile)));
			download(data, templateFile.getName(), response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace(); 
			throw new AppException(ErrorCodeEnum.FILE_DOWNLOAD_FAILD);
		}
    	return JsonData.success();
    }
    
    @RequestMapping("/downloadAllByZip")
    @ResponseBody
    public JsonData downloadAllByZip(HttpServletResponse response){
    	try {
    		byte[] data = templateFileService.getAllFilesByZip();
			download(data, "模板-"+ templateName + ".zip", response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace(); 
			throw new AppException(ErrorCodeEnum.FILE_DOWNLOAD_FAILD);
		}
    	return JsonData.success();
    }
    
    
	/**
	 * 文件下载，需要一个文件的InputStream
	 * @param inStream
	 * @param response
	 * @throws IOException 
	 */
	public static void download(byte[] data, String fileName,HttpServletResponse response) throws IOException{
		response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(),"ISO8859-1"));
		response.addHeader("Content-Length", "" + data.length);
		IOUtils.write(data, response.getOutputStream());
	}
}
